package com.gxg.services;

import com.gxg.dao.ExperimentalEnvironmentDao;
import com.gxg.dockerapi.DockerContainerAPI;
import com.gxg.entities.ExperimentalEnvironment;
import java.io.PrintStream;
import java.sql.Timestamp;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ContainerService
{
  @Autowired
  ExperimentalEnvironmentDao experimentalEnvironmentDao;
  @Value("http://192.168.2.36:2375")
  private String dockerServerIp;
  
  public String getContainerId(String documentId)
  {
    List<ExperimentalEnvironment> experimentalEnvironmentList = this.experimentalEnvironmentDao.getExperimentalEnviromentByDocument(documentId);
    if ((experimentalEnvironmentList == null) || (experimentalEnvironmentList.isEmpty())) {
      return "error:该课程暂时没有实验环境，当前使用默认实验环境.";
    }
    ExperimentalEnvironment experimentalEnvironment = (ExperimentalEnvironment)experimentalEnvironmentList.get(0);
    String imageId = experimentalEnvironment.getImageId();
    
    String containerId = null;
    
    String hostPort = String.valueOf((int)(10030.0D + Math.random() * 1001.0D));
    
    Timestamp time = new Timestamp(System.currentTimeMillis());
    String timeString = time.toString();
    String name = timeString.split(" ")[0].split("-")[0] + timeString.split(" ")[0].split("-")[1] + timeString.split(" ")[0].split("-")[2] + timeString.split(" ")[1].split(":")[0] + timeString.split(" ")[1].split(":")[1] + timeString.split(" ")[1].split(":")[2].split("\\.")[0];
    int resCode = DockerContainerAPI.createContainer(this.dockerServerIp, name, imageId, hostPort);
    if (resCode != 201) {
      return "error：实验容器创建失败，请刷新重试";
    }
    try
    {
      String resContainerInfo = DockerContainerAPI.queryContainersInfo(this.dockerServerIp);
      JSONArray jsonArray = new JSONArray(resContainerInfo);
      for (int j = 0; j < 3; j++)
      {
        for (int i = 0; i < jsonArray.length(); i++)
        {
          JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
          if (("[\"/" + name + "\"]").equals(jsonObject.get("Names").toString()))
          {
            containerId = jsonObject.getString("Id");
            break;
          }
        }
        if (containerId != null) {
          break;
        }
        Thread.sleep(1000L);
      }
      if (containerId == null) {
        return "error:创建容器失败,请刷新重试";
      }
      int resContainerCode = DockerContainerAPI.startContainer(this.dockerServerIp, containerId);
      if (resContainerCode == 204)
      {
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("port", hostPort);
        jsonObject.accumulate("containerId", containerId);
        return jsonObject.toString();
      }
      return "error:" + resContainerCode + "容器启动失败";
    }
    catch (Exception e)
    {
      System.out.println(e);
    }
    return "error:请求docker服务器出错";
  }
}
